package roadsuggester.navigation;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.client.HttpClient;

import android.location.Location;
import android.util.Log;
import roadsuggester.html.Utils;
import roadsuggester.tracks.RecordedTrack;

//Interface for the back-end database
public class NavigationInterface
{
	
	public static void addTrack(RecordedTrack recordedTrack)
	{

		StringBuilder sb=new StringBuilder();
		List<Location> locations=recordedTrack.getPath();
		for(int i=0;i<locations.size();i++)
		{
			sb.append(locations.get(i).getLatitude()+","+locations.get(i).getLongitude()+","+recordedTrack.timeAt(i));
			sb.append(":");
		}
		
		Location from=recordedTrack.from();
		Location to=recordedTrack.to();
		String data=Utils.getRequest("http://10.0.2.2:8000/tracks/addtrack/?fromLatitude="+from.getLatitude()+"&fromLongitude="+from.getLongitude()+"&toLatitude="+to.getLatitude()+"&toLongitude="+to.getLongitude()+"&timeTook="+String.valueOf(recordedTrack.timeTook())+"&pointsForMap="+sb.toString());
		if (data!="OK")
		{
			Log.e("ADDTRACK","Bad data: "+data);
			Log.e("ADDTRACK","RequestUrl: "+"http://10.0.2.2:8000/tracks/addtrack/?fromLatitude="+from.getLatitude()+"&fromLongitude="+from.getLongitude()+"&toLatitude="+to.getLatitude()+"&toLongitude="+to.getLongitude()+"&timeTook="+String.valueOf(recordedTrack.timeTook())+"&pointsForMap="+sb.toString());
		}
		
	}

	public static RecordedTrack getTrack(Location from, Location to)
	{
		//Returning null means no navigation is retrieved from the server.
		
		
		String data=Utils.getRequest("http://10.0.2.2:8000/tracks/gettrack/?fromLatitude="+from.getLatitude()+"&fromLongitude="+from.getLongitude()+"&toLatitude="+to.getLatitude()+"&toLongitude="+to.getLongitude());
		Log.e("SERVERDATA",data.length()+" - "+data);
		if (data.length()>5)
		{
			RecordedTrack track=new RecordedTrack();
			String[] rawLocations=data.split(";");
			for(int i=0;i<rawLocations.length;i++)
			{
				String[] rawData=rawLocations[i].split(",");
				if (rawLocations[i].length()>0)
				{
					double latitude=Double.parseDouble(rawData[0]);
					double longitude=Double.parseDouble(rawData[1]);
					track.addLocation(roadsuggester.main.Utils.coordsToLocation(latitude,longitude),0);
				}
			}
			return track;
		}
		else
		{
			return null;
		}
	}
}
